package com.orgcent.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.Contacts;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;

import com.orgcent.util.CharsetHelper;
import com.orgcent.util.Tools;

/**
 * 短信发送
 */
public class SMSSender extends Activity implements TextWatcher{
	/**
	 * 选择联系人时的请求码
	 */
	public static final int SMS_CONTACT_SELECT = 3;
	/**
	 * 接收SentIntent时的requestCode
	 */
	public static final int SMS_SENT_STATUS = 0;
	/**
	 * 接收DeliveryIntent时的requestCode
	 */
	public static final int SMS_delivery_STATUS = SMS_SENT_STATUS + 1;

	public static final String ACTION_SMS_SENT = "com.orgcent.sms_sent_action";
	public static final String ACTION_SMS_DELIVERY = "com.orgcent.sms_delivery_action";
	private static final String TAG = SMSReader.class.getSimpleName();

	private EditText address_et, content_et;
	private TextView content_count_tv;
	private final SmsManager sm = SmsManager.getDefault();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/**
		 * 自定义标题
		 */
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.sms_sender);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.sms_custom_title);

		content_count_tv = (TextView) findViewById(R.id.sms_content_count_tv);
		address_et = (EditText) findViewById(R.id.sms_address_et);
		content_et = (EditText) findViewById(R.id.sms_content_et);
		content_et.addTextChangedListener(this); //添加文本更改监听器
		
		controlTextInput(content_et.getEditableText());
	}

	public void btnOnClick(View view) {
		switch (view.getId()) {
		case R.id.sms_send_btn: // 发送短信
			sendSms();
			break;
		case R.id.sms_address_select_btn: // 选择联系人
			selectContact();
			break;

		default:
			break;
		}
	}

	private void sendSms() { // 发送短信
		final String address = address_et.getText().toString();
		final String content = content_et.getText().toString();

		if (TextUtils.isEmpty(address)) {
			Tools.toastShow(this, "没指定收件人");
			return;
		}
		if (TextUtils.isEmpty(content)) {
			Tools.toastShow(this, "内容为空");
			return;
		}

		final PendingIntent sentIntent = PendingIntent.getBroadcast(this,
				SMS_SENT_STATUS, new Intent(ACTION_SMS_SENT), 0); // 收到发送短信网关后要传播的Intent
		final PendingIntent deliveryIntent = PendingIntent.getBroadcast(this,
				SMS_delivery_STATUS, new Intent(ACTION_SMS_DELIVERY), 0); // 收到递送报告时要传播的Intent

		sm.sendTextMessage(address, null, content, sentIntent, deliveryIntent);
		content_et.setText("");
		address_et.setText("");
	}

	private void selectContact() { // 选择联系人
		final Intent intent = new Intent();
		intent.setAction(Intent.ACTION_PICK);
		intent.setData(Contacts.CONTENT_URI);
		startActivity(intent);
		startActivityForResult(intent, SMS_CONTACT_SELECT);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case SMS_CONTACT_SELECT:  //获取从系统联系人中选择的收件人号码
			processContactSelect(data);
			break;
		default:
			break;
		}
	}

	private void processContactSelect(Intent data) { //根据用户选择的联系人，获取其对应的号码
		Cursor c = managedQuery(data.getData(), null, null, null, null);
		boolean hasPhone = false;
		Uri phoneUri = null;
		if(c.moveToFirst()) {
			hasPhone = c.getInt(c.getColumnIndexOrThrow(Contacts.HAS_PHONE_NUMBER))==1?true:false;
			phoneUri = ContentUris.withAppendedId(CommonDataKinds.Phone.CONTENT_URI, c.getLong(c.getColumnIndex(ContactsContract.Contacts._ID)));
		}
		c.close();
		if (hasPhone && phoneUri != null) {
			c = managedQuery(phoneUri, null, null, null, null);
			while (c.moveToNext()) {                    
				address_et.append(c.getString(c.getColumnIndex(CommonDataKinds.Phone.NUMBER)));
				address_et.append(";");
			}
			c.close();
		}
	}

	@Override
	public void afterTextChanged(Editable s) { //
		controlTextInput(s);
	}

	private void controlTextInput(Editable s) {  //控制文本输入，仅ASCII字符允许160个，反之70个
		int maxLength = 160;
		String count_suffix = " / 160";
		if(!CharsetHelper.isPureAscii(s.toString())) {
			count_suffix = " / 70";
			maxLength = 70;
		}
		if(s.length() > maxLength) {
			s.delete(maxLength, s.length());
		}
		content_count_tv.setText(String.valueOf(s.length()));
		content_count_tv.append(count_suffix);
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
	}
}
